<template>
  <el-dialog :title="amend?'编辑部门':'新增部门'" :visible="showDialog" width="500px" @close="close">
    <el-form ref="departForm" label-width="140px" :model="formData" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="formData.name" placeholder="2-10个字符" style="width: 80%" size="mini" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="formData.code" placeholder="2-10个字符" style="width: 80%" size="mini" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="managerId">
        <el-select v-model="formData.managerId" placeholder="请选择负责人" style="width: 80%" size="mini">
          <el-option
            v-for="item in somesDep"
            :key="item.value"
            :label="item.username"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="formData.introduce" placeholder="1-100个字符" style="width: 80%" size="mini" type="textarea" />
      </el-form-item>

      <el-row type="flex" align="middle" justify="center">
        <el-button type="primary" @click="dispatch">确 定</el-button>
        <el-button @click="close">取 消</el-button>
      </el-row>

    </el-form>
  </el-dialog>
</template>
<script>
import { getAllDepartment, getSomeDepart, addNewDepart, getByIdDepart, updataByIdDepart } from '@/api/department'
export default {
    name: 'AddDept',
    props: {
        showDialog: {
            type: Boolean,
            default: false
        },
        parentId: { // 父级id
            type: [Number, String],
            default: null
        },
        amend: { // 弹出层标题开关
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            somesDep: [],
            formData: {
                code: 'ES', // 编号
                introduce: '此身是最为高贵之身，应许臣民一梦', // 部门介绍
                managerId: '', // 子级部门
                name: '雷电真', // 部门名
                pid: '' // 父级部门
            },
            rules: {
                code: [
                    {
                        required: true,
                        message: '必传',
                        trigger: 'blur'
                    },
                    {
                        trigger: 'blur',
                        validator: async(rule, value, callback) => {
                            if (this.amend) { // 编辑规则
                            // 先查出本次编辑对象的信息
                                // value就是输入的编码
                                let result = await getAllDepartment()
                                // 编辑场景
                                result = result.filter(item => item.id !== this.formData.id)

                                // result数组中是否存在 value值
                                if (result.some(item => item.code === value)) {
                                    callback(new Error('已经有该编码了'))
                                } else {
                                    callback()
                                }
                            } else {
                                if ((await getAllDepartment()).some(item => item.code === value)) {
                                // 未通过
                                    callback(new Error('已经有该编码了'))
                                } else {
                                // 通过
                                    callback()
                                }
                            }
                        }
                    }
                ],
                introduce: [
                    {
                        required: true,
                        message: '必传',
                        trigger: 'blur'
                    }
                ],
                managerIdId: [
                    {
                        required: true,
                        message: '必传',
                        trigger: 'blur'
                    }
                ],
                name: [
                    {
                        required: true,
                        message: '必传',
                        trigger: 'blur'
                    }
                ]
            }
        }
    },
    async created() {
        // 获取部门详情列表
        this.somesDep = await getSomeDepart()
    },
    methods: {
        // 关闭弹层
        close() {
            this.$emit('update:showDialog', false)
            setTimeout(() => {
                // 清空表单
                this.$refs.departForm.resetFields()
                // 退出编辑状态
                this.$emit('amendOff')
            }, 200)
        },
        // 新增部门或者是
        async dispatch() {
            if (this.amend) {
            // 如果这个编辑开关是打开的，那么说明需要调用对应的接口
            // 调用修改接口
                this.$refs.departForm.validate(async isRes => {
                    if (isRes) {
                        await updataByIdDepart(this.parentId, {
                            ...this.formData
                        })
                        this.$message.success('修改成功')
                        // 触发事件告知父组件刷新数据
                        this.$emit('refresh')
                        // // 关闭弹层/清空表单
                        this.close()
                    }
                })
            } else {
            // 调用接口
                this.$refs.departForm.validate(async isRes => {
                    if (isRes) {
                    // 验证成功
                        this.$nextTick(async() => {
                            console.log({
                                ...this.formData,
                                pid: this.parentId
                            })

                            await addNewDepart({
                                ...this.formData,
                                pid: this.parentId
                            })
                            this.$emit('refresh')
                            // // 关闭弹层/清空表单
                            this.close()
                        })
                    }
                })
            }
        },

        // 编辑获取数据，对象交由父组件调用
        async getByIdDepart(id) {
            // 数据交由渲染
            this.formData = await getByIdDepart(id)
        }
    }
}
</script>
